<?php
/**
 * (logic)
 */
namespace App\Logic\Amazon;

use App\Libs\RequestClient;
class GrabCommon
{
    const GRAB_ZONE_INTERVAL = 3600 * 8;

    private static $_config = [
        'report' => ['ServiceUrlSuffix'=>null,'ServiceVersion' => '2009-01-01','MWSClientVersion' => '2016-09-21'],
        'orders' => ['ServiceUrlSuffix'=>'/Orders/2013-09-01','ServiceVersion' => '2013-09-01','MWSClientVersion' => '2018-10-31'],
        'inventory' => ['ServiceUrlSuffix'=>'/FulfillmentInventory/2010-10-01','ServiceVersion' => '2010-10-01','MWSClientVersion' => '2014-09-30'],
        'products' => ['ServiceUrlSuffix'=>'/Products/2011-10-01','ServiceVersion' => '2011-10-01','MWSClientVersion' => '2017-03-22'],
        'outbound' => ['ServiceUrlSuffix'=>'/FulfillmentOutboundShipment/2010-10-01','ServiceVersion' => '2010-10-01','MWSClientVersion' => '2016-01-01'],
    ];

    /**
     * @param      $clientType
     * @param      $account
     * @return RequestClient
     */
    public static function getRequestClient($clientType,$account){
        $config = self::$_config[$clientType];
        $MWSEndpoint = $account->account_country->pluck('mws_endpoint')->last() ?? '';
        $config['ServiceURL'] = $MWSEndpoint.$config['ServiceUrlSuffix'];
        $accessKeyId = $account->amazon_area->aws_access_key_id ?? '';
        $secretAccessKey = $account->amazon_area->aws_secret_access_key ?? '';
        return new RequestClient($account->id,$accessKeyId,$secretAccessKey,$config);
    }

    /**
     * 获取请求API的服务状态
     * @param $service
     * @param $account
     * @return string
     */
    public static function getServiceStatus(RequestClient $service,$account){
        $data = $service->requestExe(['Action'=>'GetServiceStatus','SellerId'=>$account->merchant]);
        $status = isset($data['GetServiceStatusResult']['Status'])?$data['GetServiceStatusResult']['Status']:'';
        if(!($status&&($status=='GREEN'||$status=='GREEN_I'))){
            report(new \Exception('Network environment poor',117));
        }
        return $status;
    }
}
